package com.crm.dao.impl;

import com.crm.dao.IUserDao;
import com.crm.model.User;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateCallback;
import org.hibernate.Session;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public class UserDao extends BaseDao implements IUserDao {

    public void save(User user) {
        getHibernateTemplate().saveOrUpdate(user);
    }

    public List<User> getUsers() {
        return this.getHibernateTemplate().find("from User");
    }

    public User getUserByCode(String code) {
        List list = getHibernateTemplate().find("from User where userCode=?", code);
        return getUser0(list);
    }

    public List getUserByGroup(String group) {
        return getHibernateTemplate().find("from User where userGroup=?", group);
    }

    public User getUserByNameAndPwd(String name, String pwd) {
        List list = getHibernateTemplate().find("from User where username=? and password=?", new String[]{name, pwd});
        return getUser0(list);
    }

    public String getMaxUserCode() {
        List list = getHibernateTemplate().find("select max(userCode) from User");
        return list.isEmpty() ? null : (String) list.get(0);
    }

    /**
     * {@inheritDoc}
     * <li>Check and clear all of contact and process information useless before delete a user.</li>
     * <li>Check and clear all of syslog after delete a user.</li>
     */
    public void delete(User u) {
        getHibernateTemplate().deleteAll(getHibernateTemplate().find("from Process where customerName not in (select customerName from Customer)"));
        getHibernateTemplate().deleteAll(getHibernateTemplate().find("from Contact where customerName not in (select customerName from Customer)"));
        getHibernateTemplate().delete(u);
        getHibernateTemplate().deleteAll(getHibernateTemplate().find("from SysLog where userId not in (select id from User)"));
    }

    public List getUsersExceptSomebody(String userCode) {
        return getHibernateTemplate().find("select u.id,u.username," +
                "u.truename,u.jobTitle,count(c.id) from User u,Customer c " +
                "where u.id = c.user.id and userCode <> ? " +
                "group by u.id,u.username,u.truename,u.jobTitle", userCode);
    }

    public User getUserById(String id) {
        List list = getHibernateTemplate().find("from User where id=?", id);
        return getUser0(list);
    }

    private User getUser0(List list) {
        if (list.isEmpty()) {
            return null;
        } else {
            return (User) list.get(0);
        }
    }


}
